/*
 * Chastoslov
 * Copyright (C) 2009 Alexandr Stroghov
 * 
 * stroghov@gmail.com
 * 
 * This program is free software; you can redistribute it and/or modify it under the terms of the 
 * GNU General Public License, version 2, as published by the Free Software Foundation.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; 
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
 * See the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along with this program; if 
 * not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, 
 * MA 02111-1307 USA
*/
package world.ah.wf.guiclient;
import java.awt.Container;
import java.awt.Dialog;
import java.awt.Frame;
import java.awt.Dimension;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.Types;
import java.util.Arrays;
import javax.swing.JDialog;
import javax.swing.JLabel;
import java.awt.Rectangle;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class DialogNewUser extends JDialog {
  private Connection conn;
  public void setConn(Connection conn) {this.conn = conn;};
  //
  private JLabel labReaderName = new JLabel();
  private JTextField tfReaderName = new JTextField();
  private JLabel labLogin = new JLabel();
  private JTextField tfLogin = new JTextField();
  private JLabel labPassword1 = new JLabel();
  private JPasswordField tfPassword1 = new JPasswordField();
  private JPasswordField tfPassword2 = new JPasswordField();
  private JLabel labPassword2 = new JLabel();
  private JButton bClose = new JButton();
  private JButton bCreate = new JButton();
  public DialogNewUser() {this((Frame)null, "", false);}

  /**
   * 
   * @param parent
   * @param title
   * @param modal
   */
  public DialogNewUser(Frame parent, String title, boolean modal) {
    super(parent, title, modal);
    myInit();
  }
  public DialogNewUser(Dialog parent, String title, boolean modal) {
    super(parent, title, modal);  
    myInit();
  }
  //
  private void myInit() {
    try {jbInit();} catch(Exception e) {e.printStackTrace();}
    //
    // Язык (не предполагается переустановка языка во время работы с формой)
    setLang();
    // Если вызов из окна диалога, то не центрируем, а немного смещаем
    Container parent = this.getParent();
    if(parent == null || parent instanceof Frame) General.centerFrame(this);
    else this.setLocation((int)(parent.getLocation().getX() + 50),  
                          (int)(parent.getLocation().getY() + 50));
    //
  }
  //
  private void jbInit() throws Exception
  {
    this.setSize(new Dimension(400, 236));
    this.setResizable(false);
    this.getContentPane().setLayout(null);
    this.setTitle("New user");
    labReaderName.setLabelFor(tfReaderName);
    labReaderName.setBounds(new Rectangle(20, 15, 350, 15));
    labReaderName.setText("User name");
    tfReaderName.setBounds(new Rectangle(15, 30, 360, 20));
    labLogin.setLabelFor(tfLogin);
    labLogin.setBounds(new Rectangle(20, 65, 350, 15));
    labLogin.setText("Login");
    tfLogin.setBounds(new Rectangle(15, 80, 360, 20));
    labPassword1.setBounds(new Rectangle(20, 115, 170, 15));
    labPassword1.setText("Password");
    tfPassword1.setBounds(new Rectangle(15, 130, 175, 20));
    tfPassword2.setBounds(new Rectangle(200, 130, 175, 20));
    labPassword2.setBounds(new Rectangle(205, 115, 170, 15));
    labPassword2.setText("Password again");
    bClose.setText("Close");
    bClose.setBounds(new Rectangle(295, 175, 90, 25));
    bClose.setPreferredSize(new Dimension(75, 25));
    bClose.addActionListener(new ActionListener()
      {
        public void actionPerformed(ActionEvent e)
        {
          bCancel_actionPerformed(e);
        }
      });
    bCreate.setText("Create");
    bCreate.setBounds(new Rectangle(170, 175, 115, 25));
    bCreate.setPreferredSize(new Dimension(75, 25));
    bCreate.addActionListener(new ActionListener()
      {
        public void actionPerformed(ActionEvent e)
        {
          bCreate_actionPerformed(e);
        }
      });
    this.getContentPane().add(bCreate, null);
    this.getContentPane().add(bClose, null);
    this.getContentPane().add(labPassword2, null);
    this.getContentPane().add(tfPassword2, null);
    this.getContentPane().add(tfPassword1, null);
    this.getContentPane().add(labPassword1, null);
    this.getContentPane().add(tfLogin, null);
    this.getContentPane().add(labLogin, null);
    this.getContentPane().add(tfReaderName, null);
    this.getContentPane().add(labReaderName, null);
  }
  /** Устанавливает язык интерфейса */
  public void setLang() {
    String s;
    s = General.getLangItem("NewUser"); if(s.length() > 0) this.setTitle(s);
    s = General.getLangItem("UserName"); if(s.length() > 0) labReaderName.setText(s);
    s = General.getLangItem("Login"); if(s.length() > 0) labLogin.setText(s);
    s = General.getLangItem("Password"); if(s.length() > 0) labPassword1.setText(s);
    s = General.getLangItem("PasswordAgain"); if(s.length() > 0) labPassword2.setText(s); 
    s = General.getLangItem("Close"); if(s.length() > 0) bClose.setText(s);
    s = General.getLangItem("Create"); if(s.length() > 0) bCreate.setText(s);
  }

  private void bCancel_actionPerformed(ActionEvent e) {
    this.setVisible(false);
  }

  private void bCreate_actionPerformed(ActionEvent e) {
    // Проверяем одинаковость паролей 
    char[] pwd1 = tfPassword1.getPassword();
    char[] pwd2 = tfPassword2.getPassword();
    boolean passwordsAreEqual = true;
    if(pwd1.length != pwd2.length) passwordsAreEqual = false;
    else for(int i = 0; i < pwd1.length; i++) {
      if(pwd1[i] != pwd2[i]) passwordsAreEqual = false; break;
    };
    if(!passwordsAreEqual) {
      JOptionPane.showMessageDialog(this, General.getLangItem("NotEqualPasswords", 
        "Passwords are not equal"), General.getLangItem("Error", "Error") + "!", 
        JOptionPane.ERROR_MESSAGE); 
      return;
    }
    // И чтобы не пустые
    if(pwd1.length < 1) {
      JOptionPane.showMessageDialog(this, General.getLangItem("EmptyPassword", 
        "Password must not be empty"), General.getLangItem("Error", "Error") + "!", 
        JOptionPane.ERROR_MESSAGE); 
      return;
    }
    Arrays.fill(pwd2, '*');
    // Собственно добавление
    int result = -1;
    try {
      CallableStatement st = conn.prepareCall("{call CREATE_NEW_USER(?, ?, ?, ?)}");
      st.registerOutParameter(1, Types.INTEGER);
      tfLogin.setText(tfLogin.getText().trim().toLowerCase());
      st.setString(2, tfLogin.getText());
      st.setString(3, String.valueOf(pwd1));
      Arrays.fill(pwd1, '*');
      st.setString(4, tfReaderName.getText()); 
      st.executeUpdate();
      result = st.getInt(1);
      st.close();
    } catch(Exception ex) {ErrorShower.show(this, "creating a new user", "", ex); return;}
    //System.out.println("result=" + Integer.toString(result));
    // Сообщаем, что сделали
    String resultMessage;
    switch(result) {
      case 0: 
        resultMessage = General.getLangItem("createUserResult0", 
          "Nothing has been done because that user had existed \n" + 
          "and had been registered in the program before you tried to create him");
        break;
      case 1: 
        resultMessage = General.getLangItem("createUserResult1", 
          "The user has been just registered in the program. He'd existed before, \n" +
          "so he hasn't been greated and his password hasn't been changed");
        break;
      case 2: 
        resultMessage = General.getLangItem("createUserResult2", 
          "The user has been created. He had been registered before, \n" +
          "so his registration has been skipped now");
        break;
      case 3: 
        resultMessage = General.getLangItem("createUserResult3", 
          "The user has been created and registered in the program");
        break;
      default:
        resultMessage = "Logical error occured :-(";
    }
    JOptionPane.showMessageDialog(this, resultMessage, General.getLangItem("DoneExcl", "Done!"), 
      JOptionPane.INFORMATION_MESSAGE); 
  }

 
}